#!/bin/sh
#
# rtorrent          Start/Stop the rtorrent clock daemon.
#
# chkconfig: 2345 90 60
# description: rtorrent is a standard UNIX program that runs user-specified torrents

### BEGIN INIT INFO
# Provides: rtorrent
# Required-Start: $local_fs $syslog
# Required-Stop: $local_fs $syslog
# Default-Start:  2345
# Default-Stop: 90
# Short-Description: run rtorrent daemon
# Description: rtorrent is a torrent client
### END INIT INFO

USERS=`awk -F: '{print $1}' /etc/httpd/conf.d/htpasswd`
case "$1" in
    start)
	for i in $USERS; do
		if [[ ! `ps aux|grep -E "$i"|grep -v grep|grep "/bin/bash /home/$i/cron"|awk '{print $2}'` -gt 5 ]]; then
                    	sudo -u $i /usr/bin/screen -fa -d -m -S torrent /home/$i/cron
		fi
	done
        ;;
    stop)
        for i in $USERS; do
	uid=`id $i|cut -d'=' -f2|awk -F\( '{print $1}'`
		PID=`ps aux|grep -E "$i|$uid"|grep -v grep|grep "/usr/bin/SCREEN -fa -d -m -S torrent /home/$i/cron"|awk '{print $2}'`
                kill -9 $PID
	done
        ;;
    check-users|status)
	for i in $USERS; do
	uid=`id $i|cut -d'=' -f2|awk -F\( '{print $1}'`
		if [[ ! `ps aux|grep -E "$i|$uid"|grep -v grep|grep "/bin/bash /home/$i/cron"|awk '{print $2}'` -gt 5 ]]; then 
			sudo -u $i /usr/bin/screen -fa -d -m -S torrent /home/$i/cron
		fi
	done
	;;
    reload-config)
	for i in $USERS;do
	uid=`id $i|cut -d'=' -f2|awk -F\( '{print $1}'`
		PID=`ps aux|grep -E "$i|$uid"|grep -v grep|grep "bin/rtorrent"|awk '{print $2}'`
		kill -9 $PID
	done
	;;
    restart)
	for i in $USERS; do
	uid=`id $i|cut -d'=' -f2|awk -F\( '{print $1}'`
                PID=`ps aux|grep -E "$i|$uid"|grep -v grep|grep "/usr/bin/SCREEN -fa -d -m -S torrent /home/$i/cron"|awk '{print $2}'`
		kill -9 $PID
		sudo -u $i /usr/bin/screen -fa -d -m -S torrent /home/$i/cron
        done
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|reload-config|check-users}"
        exit 2
esac
exit $?